package com.intel.bluetooth;

import com.intel.surface.SettingConfig;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketService extends Thread {
    private OutputStream out;
    private InputStream in;
    private byte[] recvBuf = new byte[1024];
    private boolean mRun = false;
    private Socket serverSocket;
    private ConnectService connectService;

    public boolean connectServer(ConnectService connectService) {
        this.connectService = connectService;
        int reConnectTimes = 2;
        while (reConnectTimes > 0) {
            try {
                serverSocket = new Socket(SettingConfig.getInstance().getServerAddress(),
                                          Integer.parseInt(SettingConfig.getInstance().getServerPort()));
                out = serverSocket.getOutputStream();
                in = serverSocket.getInputStream();
                return true;
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            reConnectTimes--;
        }
        serverSocket = null;
        return false;
    }

    public void run() {
        mRun = true;
        try {
            while (mRun) {
                if (in.available() > 0) {
                    int len = in.read(recvBuf);
                    connectService.sendToDevice(recvBuf, len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized void sendBytes(byte[] buffer, int len) {
        if (out != null) {
            try {
                out.write(buffer, 0, len);
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
                connectService.closeConnection(true);
            }
        } else {
            System.err.println("tcpClient out is null");
        }
    }

    public void close() {
        try {
            mRun = false;
            in.close();
            out.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

